#!/usr/bin/env bash

# Test that npm backend properly uses bun when configured
# This test primarily verifies behavior when npm and/or bun are available

# Ensure npm is available by installing node if needed
if ! command -v npm >/dev/null 2>&1; then
	echo "npm not available in test environment, installing node..."
	# Disable GPG verification for faster test
	export MISE_GPG_VERIFY=false
	assert_succeed "mise use node@20"
fi

# Ensure bun is available
if ! command -v bun >/dev/null 2>&1; then
	echo "bun not available in test environment, installing..."
	assert_succeed "mise use bun@latest"
fi

# Test 1: With npm available but bun mode disabled (default)
echo "Testing npm backend with npm available..."
unset MISE_NPM_BUN

# Test listing versions - should succeed
assert_succeed "mise ls-remote npm:tiny >/dev/null"
echo "✓ npm backend lists versions using npm"

# Test latest version - should succeed
assert_succeed "mise latest npm:tiny >/dev/null"
echo "✓ npm backend gets latest version using npm"

# Test 2: With bun mode enabled - npm backend should still use npm for version queries
echo "Testing npm backend with bun mode enabled..."
export MISE_NPM_BUN=true

# The npm backend always uses npm for version queries (bun info requires package.json)
# This is documented in the TODOs in src/backend/npm.rs
assert_succeed "mise ls-remote npm:tiny >/dev/null"
echo "✓ npm backend uses npm for version queries even in bun mode"

# Test latest version - should succeed
assert_succeed "mise latest npm:tiny >/dev/null"
echo "✓ npm backend gets latest version using npm even in bun mode"

unset MISE_NPM_BUN

# Test 3: Test installation with bun mode
echo "Testing npm package installation with bun..."
export MISE_NPM_BUN=true

# Clean up any previous installation
mise uninstall npm:tiny@latest >/dev/null 2>&1 || true

# Install a small package using bun
assert_succeed "mise install npm:tiny@latest >/dev/null 2>&1"
echo "✓ npm backend successfully installs package using bun"

# Verify the package was installed by executing it
assert_succeed "mise exec npm:tiny@latest -- tiny --version >/dev/null"
echo "✓ Installed package can be executed"

# Clean up
mise uninstall npm:tiny@latest >/dev/null 2>&1 || true

unset MISE_NPM_BUN

# Test 4: Test installation with npm mode (default)
echo "Testing npm package installation with npm (default)..."

# Clean up any previous installation
mise uninstall npm:tiny@latest >/dev/null 2>&1 || true

# Install using npm (default)
assert_succeed "mise install npm:tiny@latest >/dev/null 2>&1"
echo "✓ npm backend successfully installs package using npm"

# Clean up
mise uninstall npm:tiny@latest >/dev/null 2>&1 || true

echo "✓ npm bun behavior test completed"
